import { createRouter, createWebHistory } from 'vue-router'
import routes from './routes'
import myTokens from '@/utils/auth'
import { checkLogin } from '@/api/login'
import NProgress from 'nprogress'
import {openLoad,closeLoad} from '@/utils/loading'
import store from '@/store'
import { useCounterStore } from '@/stores/user'
import { storeToRefs } from 'pinia'
// import type { title } from 'process'


const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes
})


router.beforeEach( async (to, from) => {
  
  if(to.path==""|| to.path=="/"){
    router.push("/index")
  }

  openLoad("请稍后");
    NProgress.start();
    console.warn = function() {}; 
    document.title=to.meta.title?to.meta.title.toString():"考试管理";
    //需要验证的
    if(!to.meta.isNotVerify){
      if(myTokens.getToken()){
         let result:any=await checkLogin();
         
         if(result.result==0){
           /**
            * pinia管理登录用户
            */
           let stores= useCounterStore();
           stores.setUser(result.data.user);
           /**
            * Vuex使用方式
            */
          //  store.commit("setUsers",{user:result.data});
           
          // sessionStorage.setItem("user",JSON.stringify(result.data))
         }else{
           return {path:"login"}
         }
      }else{
        return {path:"login"}
       } 
    }
  return true
})


router.afterEach((to, from) => {
 if(to.meta.isNotVerify){
  closeLoad();
 }else{
 }
  console.warn = function() {}; 
 NProgress.done();

})


export default router

